package com.lee.gateway.filter;

import com.lee.common.exception.ApplicationException;
import com.lee.gateway.config.AuthProperties;
import com.lee.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
// 这个注解启用一个或多个带有 @ConfigurationProperties 注解的类。它告诉 Spring Boot 应该处理和注册这些配置属性类。
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;

    private final JwtTool jwtTool;
    // Spring 提供的用于匹配路径的工具类
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 先获取 request
        ServerHttpRequest request = exchange.getRequest();
        // 根据请求路径判断是否需要拦截
        if (isExclude(request.getPath().toString())) {
            // 不需要直接放行
            return chain.filter(exchange);
        }
        // 判断请求头中是否存在 tocken
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
        if (authorization != null && !authorization.isEmpty()) {
            token = authorization.get(0);
        }
        // 校验 tocken
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (ApplicationException e) {
            // 校验失败，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // tocken 有效向下传递用户信息 (通过请求头)
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("user-info", userInfo))
                .build();
        System.out.println("获取到用户 id = " + userId);

        // 最后放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern,path)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
